package com.kly.smartbi.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.kly.smartbi.constant.CommonConstant.LOCK_PREFIX;

/**
 * @author admin
 * @date 2025/4/9
 */
public class SimpleRedisLock {

    private final StringRedisTemplate stringRedisTemplate;

    private final String uuid = UUID.randomUUID().toString();

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    /**
     * 获取锁
     */
    public boolean tryLock(String keyPrefix, Integer expireTime) {
        String threadId = Thread.currentThread().getId() + "-" + uuid;
        String key = LOCK_PREFIX + keyPrefix;
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, threadId, expireTime, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 释放锁
     */
    public void unLock(String keyPrefix) {
       // stringRedisTemplate.execute(
       //         UNLOCK_SCRIPT,
       //         Collections.singletonList(LOCK_PREFIX + keyPrefix),
       //         Thread.currentThread().getId() + "-" + uuid
       // );
        String key = LOCK_PREFIX + keyPrefix;
        String threadId = Thread.currentThread().getId() + "-" + uuid;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if( threadId.equals(cache)) {
            stringRedisTemplate.delete(key);
        }
    }
}
